/**
 * 
 */
package soa.security.dao.impl;

import javax.annotation.Resource;
import javax.naming.Name;

import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.support.LdapNameBuilder;
import org.springframework.stereotype.Repository;

import soa.security.dao.OrganizationUnitDao;
import soa.security.domain.Organization;
import soa.security.domain.OrganizationUnit;
import soa.security.domain.Region;

/**
 * @author Cre.Gu
 *
 */
@Repository
public class OrganizationUnitDaoImpl implements OrganizationUnitDao {

	@Resource
	private LdapTemplate ldapTemplate;

	/*
	 * (non-Javadoc)
	 * 
	 * @see soa.security.dao.OrganizationUnitDao#create(soa.security.domain.
	 * OrganizationUnit)
	 */
	@Override
	public void create(Organization organization, OrganizationUnit t) {
		t.setDn(LdapNameBuilder.newInstance(organization.getDn())
				.add("ou", t.getOu()).build());

		ldapTemplate.create(t);
	}

	@Override
	public OrganizationUnit findBy(Organization organization, String ou) {
		try {
			Name dn = LdapNameBuilder.newInstance(organization.getDn())
					.add("ou", ou).build();

			return ldapTemplate.findByDn(dn, OrganizationUnit.class);
		} catch (Exception e) {
			return null;
		}

	}

	@Override
	public void create_region(Region region, OrganizationUnit t) {
		t.setDn(LdapNameBuilder.newInstance(region.getDn())
				.add("ou", t.getOu()).build());

		ldapTemplate.create(t);		
	}

	@Override
	public OrganizationUnit findBy(Region region, String ou) {
		try {
			Name dn = LdapNameBuilder.newInstance(region.getDn())
					.add("ou", ou).build();

			return ldapTemplate.findByDn(dn, OrganizationUnit.class);
		} catch (Exception e) {
			return null;
		}
	}

}
